<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ChinaMap</title>
    <script type="text/javascript" src="../lib/d3.js"></script>
    <script type="text/javascript" src="../lib/topojson.js"></script>
</head>
<body>
<script type="text/javascript">
    var width = 1000;
    var height = 1000;

    var svg = d3.select("body")
        .append("svg")
        .attr("width",width)
        .attr("height",height)
        .append("g")
        .attr("transform","translate(0,0)");


    var projection = d3.geo.mercator()
        .center([107,31])
        .scale(850)
        .translate([width/2,height/2]);

    var path = d3.geo.path().projection(projection);

    d3.json("../geojson/china.topojson",function (error,toporoot) {
        if (error)
            console.log(error);

        var georoot = topojson.feature(toporoot,toporoot.objects.china);

        svg.selectAll("path")
            .data(georoot.features)
            .enter()
            .append("path")
            .attr("class","province")
            .attr("d",path)
            .style("fill","#ccc")
            .style("stroke","steelblue")
            .on("click",function (d) {

                //看看能不能实现点击一个区域的时候去掉其他所有边界框和点
                d3.selectAll("rect,circle").remove();
//                d3.selectAll("circle").remove();


                //计算面积，中心，边界框
                var area = path.area(d);
                var centroid = path.centroid(d);
                var bounds = path.bounds(d);

                //输出到console
                console.log("省份："+d.properties.name);
                console.log("面积："+area);
                console.log("中心："+centroid);
                console.log("边界框：");
                console.log(bounds);

                //显示中心
                svg.append("circle")
                    .attr("class","centroid")
                    .attr("cx",centroid[0])
                    .attr("cy",centroid[1])
                    .style("fill","white")
                    .attr("r",8);

                //显示边界框
                svg.append("rect")
                    .attr("class","boundingbox")
                    .attr("x",bounds[0][0])
                    .attr("y",bounds[0][1])
                    .style("fill","none")
                    .style("stroke","steelblue")
                    .style("stroke-width","5")
                    .attr("width",bounds[1][0]-bounds[0][0])
                    .attr("height",bounds[1][1]-bounds[0][1]);
            });

    });
</script>
</body>
</html>